import AppInfo from "../../appInfo.js"
import NetTool from '@/common/js/axion.js'
export const getFileCache = function(filePath, fileName, fileType) {
	//  缓存key值 
	let storageKey = 'FILE_CACHE_INFO_' + fileName + fileType
	// 首先获取本地存储的数据，查询是否有对应文件路径，如果有缓存内容，直接返回
	const cacheFileInfo = uni.getStorageSync(storageKey)
	if (cacheFileInfo) {
		console.log("已缓存为：" + cacheFileInfo)
		return cacheFileInfo
	} else {
		console.log("未缓存,进行下载保存")
		// 如果没有，执行下载，并存储起来后
		uni.downloadFile({
			url: filePath,
			success: (res) => {
				if (res.statusCode === 200) {
					console.log('下载成功');
					// 再进行本地保存
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: function(res2) {
							console.log(res2.savedFilePath)
							uni.setStorageSync(storageKey, res2.savedFilePath)
							return res2.savedFilePath
						},
						fail: function(res2) {
							uni.$u.toast('缓存失败，请检查储存权限')
							return filePath
						}
					})
				} else {
					console.log('下载临时文件失败')
					return filePath
				}
			},
			fail: (res) => {
				uni.$u.toast('缓存失败，请检查储存权限')
				console.log(res)
				return filePath
			}
		})
	}

}
export const upadteApp = function(fn) {

	let appInfo = AppInfo
	let mNetTool = new NetTool()
	let getVer = function(str) {
		let newStr = ''
		for (let item of str) {
			if (typeof(item - 0) == 'number' && !isNaN((item - 0))) {
				newStr += item
			}
		}

		return newStr
	}
	let nversion = Number(getVer(appInfo.version))
	let version
	// let appName = appInfo.appName
	console.log('appName', appName)
	mNetTool.get('capi/V2/sysSetting/coreAppUpdate/nf/list', {
		name: appName
	}, res => {

		if (res.rows.length == 0) {
			// uni.$u.toast('暂无更新')
			typeof fn == 'function' && fn(res);
		} else {
			version = res.rows[0].version_code
			if (nversion == version) {
				uni.$u.toast('当前已是最新版')
			} else if (nversion < version) {
				uni.hideLoading()
				if (!res.rows[0].remark) {
					res.rows[0].remark = ' '
				}
				uni.showModal({
					title: '提示',
					content: '有新的版本是否更新。' + res.rows[0].remark,
					showCancel: true,
					cancelText: '取消',
					confirmText: '更新',
					success: r => {
						if (r.confirm) {
							UpdateOfWgt(res.rows[0])
						}
					},
					fail: () => {},
					complete: () => {}
				});
			}
		}
	})

	let UpdateOfWgt = function(data) {
		// #ifdef APP-PLUS
		const downloadTask = uni.downloadFile({
			url: data.url,
			success: (downloadResult) => {
				uni.hideLoading()
				if (downloadResult.statusCode === 200) {
					console.log("增量更新包下载成功，即将安装: " + JSON.stringify(downloadResult, null, 4));
					plus.runtime.install(downloadResult.tempFilePath, {
						force: false
					}, function() {
						console.log("增量更新成功,将重启app");
						plus.runtime.restart();
					}, function(e) {
						console.error('增量更新安装失败：' + JSON.stringify(e));
					});
				}
				uni.hideLoading()
			},

		});
		let pass = 0
		uni.showLoading({
			title: '下载进度' + pass.toFixed(0) + '%'
		})
		downloadTask.onProgressUpdate((res) => {
			pass = res.totalBytesWritten / res.totalBytesExpectedToWrite
			// console.log('下载进度' + progress);

			console.log('已经下载的数据长度' + res.totalBytesWritten);
			console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
		});
		// #endif

	}
}
/**
 * @param {Object} arr 数组
 * @param {Object} num 层数
 * @param {Object} fn 返回新数组
 */
export const arrLayered = function(arr, num, fn) {
	let all = []
	let it = []
	arr.forEach((v, i) => {
		i++
		if (i % 8 == 0 && i != 0) {
			it.push(v)
			all.push(it)
			it = []
		} else {
			it.push(v)
		}
	})
	if (it.length > 0) {
		all.push(it)
	}
	typeof fn == 'function' && fn(all)
}
/**
 * 文件上传
 * @param {Object} url 文件地址
 * @param {Object} fn 返回一个地址
 */
export const uploadFile = function(url, fn) {

	return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
			url: 'https://api.iloomo.com/capi/tools/public/fileUpload?token=08fee81482a84d388029f67ed57490cf', // 仅为示例，非真实的接口地址
			filePath: url,
			name: 'file',
			formData: {
				user: 'test'
			},
			success: (res) => {
				console.log(JSON.parse(res.data))
				setTimeout(() => {
					resolve(JSON.parse(res.data))
				}, 1000)
			}
		});
	})
}
/**
 * 震动uniapp App端
 * @param {Object} num 震动次数 
 * @param {Object} fn 回调函数
 */
export const vbshort = function(num, fn) {
	// #ifdef APP
	let i = 0
	i++
	let toVibrate = function() {
		uni.vibrate({
			success: function() {
				typeof fn == 'function' && fn(i)
			}
		});
	}
	if (i <= num) {
		toVibrate()
	}
	// #endif
	// #ifdef MP
	uni.$u.toast('触发震动，请在移动端查看效果')
	// #endif
}
/**
 * 
 */
const Audio = uni.createInnerAudioContext();
// var AipSpeechClient = require("baidu-aip-sdk").speech;
// 设置APPID/AK/SK
// var APP_ID = "25599013";
// var API_KEY = "2zgL5Otmo02KezduLGv4wAyd";
// var SECRET_KEY = "dFQmuRaKR3GK7PK4nre9YbS7cz6uXZFB ";
// var client = new AipSpeechClient(APP_ID, API_KEY, SECRET_KEY);
import Voice from './QS-baiduyy.js' /* QS-baiduyy.js 地址 */
let bdyytok = uni.getStorageSync('bdyytok')
export const playAudioText = function(string, fn) {
	if (!bdyytok) {
		Voice(1231312)
	}
	bdyytok = uni.getStorageSync('bdyytok')
	uni.vibrateLong();
	if (!string) {
		Audio.pause()
		return
	}
	let text = string
	let url = 'http://tsn.baidu.com/text2audio?tex=' + text + '&per=0&spd=5&pit=5&vol=5&aue=3&cuid=123456PHP&tok=' +
		bdyytok + '&lan=zh&ctp=1'
	console.log('url', url)
	Audio.pause()
	Audio.sessionCategory = 'playback'
	Audio.autoplay = true;
	Audio.src = url; //音频地址  
	Audio.play(); //执行播放   
	Audio.onPause(function() {
		// console.log('end');
		// Audio.src = url; //音频地址

	});
	typeof fn == 'function' && fn()
}
export const playAudioUrl = function(url) {
	if (!url) {
		Audio.pause()
		return
	} 
	Audio.pause()
	Audio.sessionCategory = 'playback'
	Audio.autoplay = true;
	Audio.src = url; //音频地址  
	Audio.play(); //执行播放   
	Audio.onPause(function() {
		// console.log('end');
		// Audio.src = url; //音频地址
	
	});
}
export const getAudioUrl = function(text) {
	if (!bdyytok) {
		Voice(1231312)
	}
	 bdyytok = uni.getStorageSync('bdyytok')
	 if(bdyytok){
		let url = 'http://tsn.baidu.com/text2audio?tex=' + text + '&per=0&spd=5&pit=5&vol=5&aue=3&cuid=123456PHP&tok=' + bdyytok + '&lan=zh&ctp=1'
		return url
	 }else{
		 return 400
	 }
}
let _debounceTimeout = null,
	_throttleRunning = false
/**
 * @param {Object} arr 传进来的对象数组
 * @param {Object} fn  回调
 */
export const arrObjSet = function(arr, fn) {
	let nArr = producterList.filter((element, index, self) => {
		return self.findIndex(x => x.manufacturer === element.manufacturer) === index
	})
	typeof fn == 'function' && fn(nArr);
}
/**
 * 防抖
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms   
 */
export const debounce = (fn, delay = 500) => {
	clearTimeout(_debounceTimeout);
	_debounceTimeout = setTimeout(() => {
		typeof fn == 'function' && fn();
	}, delay);
}
/**
 * 节流
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms  
 */
export const throttle = (fn, delay = 500) => {
	if (_throttleRunning) {
		return;
	}
	_throttleRunning = true;
	typeof fn == 'function' && fn();
	setTimeout(() => {
		_throttleRunning = false;
	}, delay);
}
/**
 * toast
 */
export const msg = (title = '', param = {}) => {
	if (!title) return;
	uni.showToast({
		title,
		duration: param.duration || 1500,
		mask: param.mask || false,
		icon: param.icon || 'none'
	});
}
/**
 * 检查登录
 * @return {Boolean}
 */
export const isLogin = (options = {}) => {
	const token = uni.getStorageSync('uniIdToken');
	if (token) {
		return true;
	}
	if (options.nav !== false) {
		uni.navigateTo({
			url: '/pages/auth/login'
		})
	}
	return false;
}
/**
 * 获取页面栈
 * @param {Number} preIndex为1时获取上一页
 * @return {Object} 
 */
export const prePage = (preIndex = 1) => {
	const pages = getCurrentPages();
	const prePage = pages[pages.length - (preIndex + 1)];

	return prePage.$vm;
}
export const dealDate = (dateTime) => {
	//回头搞个这则吧。

	if (dateTime.indexOf('-') != -1) {
		dateTime = dateTime.replace(/-/g, "/")
	}
	if (dateTime.indexOf('年') != -1) {
		dateTime = dateTime.replace("年", "/")
	}
	if (dateTime.indexOf('月') != -1) {
		dateTime = dateTime.replace("月", "/")
	}
	if (dateTime.indexOf('日') != -1) {
		dateTime = dateTime.replace("日", "")
	}

	return dateTime;
	// return day<0?"投票已结束":day;
}

/**
 * 格式化时间戳 Y-m-d H:i:s
 * @param {String} format Y-m-d H:i:s
 * @param {Number} timestamp 时间戳   
 * @return {String}
 */
export const date = (format, timeStamp) => {
	if ('' + timeStamp.length <= 10) {
		timeStamp = +timeStamp * 1000;
	} else {
		timeStamp = +timeStamp;
	}
	let _date = new Date(timeStamp),
		Y = _date.getFullYear(),
		m = _date.getMonth() + 1,
		d = _date.getDate(),
		H = _date.getHours(),
		i = _date.getMinutes(),
		s = _date.getSeconds();

	m = m < 10 ? '0' + m : m;
	d = d < 10 ? '0' + d : d;
	H = H < 10 ? '0' + H : H;
	i = i < 10 ? '0' + i : i;
	s = s < 10 ? '0' + s : s;

	return format.replace(/[YmdHis]/g, key => {
		return {
			Y,
			m,
			d,
			H,
			i,
			s
		} [key];
	});
}
//二维数组去重
export const getUnique = array => {
	let obj = {}
	return array.filter((item, index) => {
		let newItem = item + JSON.stringify(item)
		return obj.hasOwnProperty(newItem) ? false : obj[newItem] = true
	})
}
// 判断类型集合
export const checkStr = (str, type) => {
	switch (type) {
		case 'mobile': //手机号码
			return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
		case 'tel': //座机
			return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
		case 'card': //身份证
			return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
		case 'mobileCode': //6位数字验证码
			return /^[0-9]{6}$/.test(str)
		case 'pwd': //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
			return /^([a-zA-Z0-9_]){6,18}$/.test(str)
		case 'payPwd': //支付密码 6位纯数字
			return /^[0-9]{6}$/.test(str)
		case 'postal': //邮政编码
			return /[1-9]\d{5}(?!\d)/.test(str);
		case 'QQ': //QQ号
			return /^[1-9][0-9]{4,9}$/.test(str);
		case 'email': //邮箱
			return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
		case 'money': //金额(小数点2位)
			return /^\d*(?:\.\d{0,2})?$/.test(str);
		case 'URL': //网址
			return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
		case 'IP': //IP
			return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
		case 'date': //日期时间
			return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) ||
				/^(\d{4})\-(\d{2})\-(\d{2})$/
				.test(str)
		case 'number': //数字
			return /^[0-9]$/.test(str);
		case 'english': //英文
			return /^[a-zA-Z]+$/.test(str);
		case 'chinese': //中文
			return /^[\\u4E00-\\u9FA5]+$/.test(str);
		case 'lower': //小写
			return /^[a-z]+$/.test(str);
		case 'upper': //大写
			return /^[A-Z]+$/.test(str);
		case 'HTML': //HTML标记
			return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
		default:
			return true;
	}
}
